<?php

namespace cccmvc;

use cccmvc\exception\DatabaseException;
use cccmvc\exception\NotFoundException;

class Application
{
    public static Application $app;
    public static string $appNamespace;
    public static string $ROOT_PATH;
    public Database $database;
    public Router $router;
    public Request $request;
    public View $view;
    public Response $response;
    public Session $session;

    /**
     * @throws DatabaseException
     */
    public function __construct($rootPath, $config = [])
    {
        self::$app = $this;
        self::$ROOT_PATH = $rootPath;
        self::$appNamespace = $config['app_namespace'];

        $this->request = new Request();
        $this->response = new Response();
        $this->router = new Router($this->request, $this->response);
        $this->database = new Database($config['db']);
        $this->view = new View($config['view']);
        $this->session = new Session();
    }

    public function run()
    {
        try {
            $this->router->resolve();

        } catch (NotFoundException $e) {
            $this->response->setStatusCode($e->getCode());
        } catch (DatabaseException $e) {
            $this->response->setStatusCode(500);
        }
    }
}